package com.daichi.yygh.msm.controller;

import com.daichi.yygh.common.result.Result;
import com.daichi.yygh.msm.service.MsmService;
import com.daichi.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api(tags = "短信相关接口")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    private final MsmService msmService;

    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public MsmApiController(MsmService msmService, RedisTemplate<String, String> redisTemplate) {
        this.msmService = msmService;
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //从redis获取验证码，如果获取获取到，返回ok
        String code = redisTemplate.opsForValue().get(phone);
        if (StringUtils.hasLength(code)) {
            return Result.ok();
        }

        //如果从redis获取不到，则生成验证码，并放到redis中
        code = RandomUtil.getSixBitRandom();
        boolean success = msmService.send(phone, code);
        if (success) {
            redisTemplate.opsForValue().set(phone, code, 3, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }
    }


}
